package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.config.DongDongSearchConfig;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.service.item.ItemService;
import com.dongdongshop.service.item_jpa.ItemJpaService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@RocketMQMessageListener(topic = "item-create-es",consumerGroup = "my-consumer-item-create-es")
public class EsCreateController implements RocketMQListener<Long[]> {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Reference
    private ItemService itemService;
    @Reference
    private ItemJpaService itemJpaService;
    @Override
    public void onMessage(Long[] longs) {
        for (Long aLong : longs) {
           /* List<TbItem> list = itemService.listItemByGoodsId(aLong);*/
            List<TbItem> list = itemJpaService.listItemByGoodsId(aLong);
            for (TbItem item : list) {
                IndexRequest request = new IndexRequest("shopindex", "doc", item.getId().toString());
                //方式1
                //request.source("userName","zhangsan","age","18");
                try {
                    //方式二
                    String userJson = new ObjectMapper().writeValueAsString(item);
                    request.source(userJson, XContentType.JSON);
                    //执行操作
                    IndexResponse response = restHighLevelClient.index(request, DongDongSearchConfig.COMMON_OPTIONS);
                    //提取有用的响应信息
                    System.out.println(">>>index: "+response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
